package com.jf.service.impl;

import com.jf.bean.Project2;
import com.jf.bean.ProjectImg;
import com.jf.dao.Project2Dao;
import com.jf.dao.ProjectImgDao;
import com.jf.dao.impl.Project2DaoImpl;
import com.jf.dao.impl.ProjectImgDaoImpl;
import com.jf.service.Project2Service;
import com.jf.util.MyUtils;
import com.jf.util.PageInfo;
import com.jf.util.ResultJson;

import java.util.ArrayList;
import java.util.List;

public class Project2ServiceImpl implements Project2Service {
    private Project2Dao project2Dao = new Project2DaoImpl();

    private ProjectImgDao projectImgDao = new ProjectImgDaoImpl();
    @Override
    public ResultJson getPage(PageInfo pageInfo, Project2 project2) {
        List<Project2> list = project2Dao.getPage(pageInfo,project2);
        int count = project2Dao.getCount(project2);
        pageInfo.setPageData(list,count);
        return ResultJson.success(pageInfo);
    }

    @Override
    public ResultJson info(String id) {
        Project2 project2 = project2Dao.getById(id);
        List<ProjectImg> piList = projectImgDao.getListByProjectId(id);
        project2.setProjectImgList(piList);

        return ResultJson.success(project2);
    }

    @Override
    public ResultJson saveOrUpdate(Project2 project2) {
        int result;
        if(MyUtils.isStringEmpty(project2.getId())){
            /*id非自增，使用uuid实现，在未执行SQL前，就可以知道ID的确切值*/
            /*这里必须手动设置id*/
            project2.setId(MyUtils.getUUID());
            result = project2Dao.addSelect(project2);

        }else{
            result = project2Dao.updateSelect(project2);
            projectImgDao.deleteByProjectId(project2.getId());
        }
        // 批量处理图片表的数据
        if(project2.getImgs() != null && project2.getImgs().length > 0){
            List<ProjectImg> list = new ArrayList<>();
            for(String img : project2.getImgs()){
                ProjectImg pi = new ProjectImg();
                pi.setProjectId(project2.getId());
                pi.setSrc(img);
                list.add(pi);
            }
            projectImgDao.batchInsert(list);
        }
        return result > 0 ? ResultJson.success():ResultJson.error("操作失败！");
    }

    @Override
    public ResultJson delete(String[] ids) {
        int result = project2Dao.batchDelete(ids);
        return result == ids.length ? ResultJson.success():ResultJson.error("删除异常！");
    }

    @Override
    public ResultJson getList() {
        List<Project2> list = project2Dao.getList();
        for (Project2 project2 : list){
            project2.setProjectImgList(projectImgDao.getListByProjectId(project2.getId()));
        }
        return ResultJson.success(list);
    }
}
